from web.models.user import Group, Association, User, Information
from web.views.api import route_api
from flask import request, jsonify
from application import app, db
from datetime import datetime


@route_api.route("/group/index")
def group_index():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req["user_id"]) if "user_id" in req else -1
    if user_id <= 0:
        resp["code"] = -1
        resp["msg"] = "操作错误"
        return jsonify(resp)

    # 获取用户管理的群组
    manager_group_list = Group.query.filter_by(manager_id=user_id, status=1).all()
    manager_group_data_list = []
    if manager_group_list:
        for item in manager_group_list:
            tmp_data = {
                'gid': item.gid,
                'name': item.name,
                'avatar': item.avatar
            }
            manager_group_data_list.append(tmp_data)
    resp['data']['manager_group_data_list'] = manager_group_data_list

    # 获取用户加入的群组
    member_group_list = Association.query.filter_by(user_id=user_id, status=1).all()
    group_id_list = []
    member_group_data_list = []
    if member_group_list:
        for item in member_group_list:
            group_id_list.append(item.group_id)
    for gid in group_id_list:
        item_group = Group.query.filter_by(gid=gid, status=1).first()
        tmp_data = {
            'gid': item_group.gid,
            'name': item_group.name,
            'avatar': item_group.avatar
        }
        member_group_data_list.append(tmp_data)

    resp['data']['member_group_data_list'] = member_group_data_list

    return jsonify(resp)


@route_api.route("/group/group-set", methods=["GET", "POST"])
def set_group():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    gid = int(req['gid']) if 'gid' in req else None
    manager_id = int(req["manager_id"]) if "manager_id" in req else None
    group_name = req["group_name"] if "group_name" in req else None
    group_detail = req["group_detail"] if "group_detail" in req else ""

    if not manager_id or not gid:
        resp['code'] = -1
        resp['msg'] = "操作失败"
        return jsonify(resp)
    if not group_name:
        resp['code'] = -1
        resp['msg'] = "群昵称不能为空"
        return jsonify(resp)
    if len(group_name) > 10:
        resp['code'] = -1
        resp['msg'] = "群昵称不能超过10个字"
        return jsonify(resp)
    if len(group_detail) > 100:
        resp['code'] = -1
        resp['msg'] = "简介不能超过100个字"
        return jsonify(resp)

    group = Group.query.filter_by(gid=gid, status=1).first()
    # 创建群组
    if not group:
        with db.auto_commit():
            # 插入数据库
            group = Group(manager_id=manager_id, name=group_name, avatar=app.config['DEFAULT_AVATAR'],
                          detail=group_detail, created_time=datetime.now(), status=1)
            db.session.add(group)
        with db.auto_commit():
            # 添加创建群消息
            inf = Information(user_id=manager_id, member_id=manager_id, manager_id=manager_id, group_id=group.gid,
                              created_time=datetime.now(),
                              inform_type=0, status=1, is_read=0, done_type=0, is_manager=1)
            db.session.add(inf)

        return jsonify(resp)
    # 修改群组信息
    else:
        group.name = group_name
        group.detail = group_detail
        db.session.add(group)
        return jsonify(resp)


@route_api.route("/group/info")
def group_info():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    group_id = int(req['group_id']) if "group_id" in req else -1

    # 返回群的信息与管理员信息
    group_info = Group.query.filter_by(gid=group_id, status=1).first()
    if not group_info:
        resp['code'] = -1
        resp['msg'] = "该群不存在"
        return jsonify(resp)
    group_manager_id = group_info.manager_id
    group_manager_info = User.query.filter_by(uid=group_manager_id).first()
    resp['data']['group_info'] = {
        "name": group_info.name,
        "avatar": group_info.avatar,
        "detail": group_info.detail,
        "created_time": group_info.created_time,
        "manager_id": group_manager_id,
        "manager_name": group_manager_info.nickname,
        "manager_avatar": group_manager_info.avatar
    }

    # 返回群成员信息列表
    association_list = Association.query.filter_by(group_id=group_id, status=1).all()
    group_member_uid_list = []
    if association_list:
        for item in association_list:
            group_member_uid_list.append(item.user_id)
    member_info_list = []
    for item_user_id in group_member_uid_list:
        user_info = User.query.filter_by(uid=item_user_id).first()
        item_data = {
            "user_id": item_user_id,
            "nickname": user_info.nickname,
            "avatar": user_info.avatar,
            "sex": user_info.sex,
        }
        member_info_list.append(item_data)

    resp['data']['member_info_list'] = member_info_list

    return resp


@route_api.route("/group/search")
def group_search():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    group_id = int(req['group_id']) if "group_id" in req else -1
    if group_id <= 0:
        resp['code'] = -1
        resp['msg'] = "未收到群ID"
        return jsonify(resp)

    group = Group.query.filter_by(gid=group_id, status=1).first()
    if not group:
        resp['data']['group_data'] = {}
        return jsonify(resp)

    group_info = {
        'name': group.name,
        'avatar': group.avatar
    }
    resp['data']['group_data'] = group_info

    return jsonify(resp)


@route_api.route("/group/join-request")
def join_request():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    group_id = int(req['group_id']) if "group_id" in req else -1
    user_id = int(req['user_id']) if "user_id" in req else -1
    if group_id <= 0 or group_id <= 0:
        resp['code'] = -1
        resp['msg'] = "操作错误"
        return jsonify(resp)

    manager_id = Group.query.filter_by(gid=group_id, status=1).first().manager_id
    with db.auto_commit():
        join_inf_manager = Information(user_id=manager_id, member_id=user_id, manager_id=manager_id, group_id=group_id,
                                       created_time=datetime.now(),
                                       inform_type=2, status=1, is_read=0, done_type=0, is_manager=1)
        join_inf_member = Information(user_id=user_id, member_id=user_id, manager_id=manager_id, group_id=group_id,
                                      created_time=datetime.now(),
                                      inform_type=2, status=1, is_read=0, done_type=0, is_manager=0)
        db.session.add_all([join_inf_manager, join_inf_member])
    with db.auto_commit():
        join_inf_manager.ass_id = join_inf_member.id
        join_inf_member.ass_id = join_inf_manager.id
        db.session.add_all([join_inf_manager, join_inf_member])

    return jsonify(resp)


@route_api.route("/group/join-agree")
def join_agree():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    group_id = int(req['group_id']) if "group_id" in req else -1
    user_id = int(req['user_id']) if "user_id" in req else -1
    is_agree = int(req['is_agree']) if "is_agree" in req else -1
    inf_id = int(req['inf_id']) if "inf_id" in req else -1

    if inf_id <= 0 or group_id <= 0 or user_id <= 0:
        resp['code'] = -1
        resp['msg'] = "操作错误"
        return jsonify(resp)

    with db.auto_commit():
        tar_manager_inf = Information.query.filter_by(id=inf_id).first()
        tar_member_inf = Information.query.filter_by(id=tar_manager_inf.ass_id).first()

        if not is_agree:
            tar_manager_inf.done_type = 2  # 更改为已拒绝
            tar_member_inf.done_type = 2
            db.session.add_all([tar_manager_inf, tar_member_inf])
            return jsonify(resp)

        tar_ass = Association.query.filter_by(user_id=user_id, group_id=group_id, status=1).first()
        if tar_ass:
            tar_manager_inf.status = 0
            tar_member_inf.status = 0
            db.session.add_all([tar_manager_inf, tar_member_inf])

            resp['code'] = -1
            resp['msg'] = "用户已经是群成员"
            return jsonify(resp)

        tar_group = Group.query.filter_by(gid=group_id, status=1).first()
        if not tar_group:
            resp['code'] = -1
            resp['msg'] = "该群已解散"
            return jsonify(resp)

        tar_manager_inf.done_type = 1  # 更改为已同意
        tar_member_inf.done_type = 1
        association = Association(group_id=group_id, user_id=user_id, status=1)

        db.session.add_all([tar_manager_inf, tar_member_inf, association])
        return jsonify(resp)


@route_api.route("/group/remove-group")
def remove_group():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    group_id = int(req['group_id']) if 'group_id' in req else -1
    if group_id <= 0:
        resp['code'] = -1
        resp['msg'] = '操作错误'
        return jsonify(resp)

    with db.auto_commit():
        tar_group = Group.query.filter_by(gid=group_id, status=1).first()
        if not tar_group:
            resp['code'] = -1
            resp['msg'] = '该群组不存在'
            return jsonify(resp)
        manager_id = tar_group.manager_id
        # 创建消息 管理员
        remove_inf = Information(user_id=manager_id, member_id=manager_id, manager_id=manager_id, group_id=group_id,
                                 status=1, is_read=0, inform_type=1, done_type=1, is_manager=1,
                                 created_time=datetime.now())
        tar_group.status = 0  # 删除群组
        db.session.add_all([remove_inf, tar_group])

        tar_ass_list = Association.query.filter_by(group_id=group_id).all()
        if tar_ass_list:
            for tar_ass in tar_ass_list:
                tar_ass.status = 0
                # 创建消息 成员
                inf = Information(user_id=tar_ass.user_id, member_id=tar_ass.user_id, manager_id=manager_id,
                                  group_id=group_id, status=1, is_read=0, inform_type=1, done_type=1, is_manager=0,
                                  created_time=datetime.now())
                db.session.add_all([tar_ass, inf])

    return jsonify(resp)


@route_api.route("/group/quit-group")
def quit_group():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req['user_id']) if 'user_id' in req else -1
    group_id = int(req['group_id']) if 'group_id' in req else -1
    if user_id <= 0 or group_id <= 0:
        resp['code'] = -1
        resp['msg'] = '操作错误'
        return jsonify(resp)

    manager_id = Group.query.filter_by(gid=group_id).first().manager_id
    if user_id == manager_id:
        resp['code'] = -1
        resp['msg'] = '管理员不能直接退群'
        return jsonify(resp)

    with db.auto_commit():
        tar_ass = Association.query.filter_by(user_id=user_id, group_id=group_id, status=1).first()
        if not tar_ass:
            resp['code'] = -1
            resp['msg'] = "你不是该群的成员"
            return jsonify(resp)

        tar_ass.status = 0
        inf_manager = Information(user_id=manager_id, member_id=user_id, manager_id=manager_id,
                                  group_id=group_id, status=1, is_read=0, inform_type=1, done_type=0, is_manager=1,
                                  created_time=datetime.now())
        inf_member = Information(user_id=user_id, member_id=user_id, manager_id=manager_id, group_id=group_id,
                                 is_manager=0, status=1, is_read=0, inform_type=1, done_type=0,
                                 created_time=datetime.now())

        db.session.add_all([tar_ass, inf_manager, inf_member])

    return jsonify(resp)


@route_api.route("/group/remove-member")
def remove_member():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req['user_id']) if 'user_id' in req else -1
    group_id = int(req['group_id']) if 'group_id' in req else -1
    if user_id <= 0 or group_id <= 0:
        resp['code'] = -1
        resp['msg'] = '操作错误'
        return jsonify(resp)

    manager_id = Group.query.filter_by(gid=group_id).first().manager_id
    with db.auto_commit():
        tar_ass = Association.query.filter_by(user_id=user_id, group_id=group_id, status=1).first()
        tar_ass.status = 0

        inf_manager = Information(user_id=manager_id, member_id=user_id, manager_id=manager_id,
                                  group_id=group_id, status=1, is_read=0, inform_type=1, done_type=2, is_manager=1,
                                  created_time=datetime.now())
        inf_member = Information(user_id=user_id, member_id=user_id, manager_id=manager_id, group_id=group_id,
                                 is_manager=0, status=1, is_read=0, inform_type=1, done_type=2,
                                 created_time=datetime.now())

        db.session.add_all([tar_ass, inf_manager, inf_member])

    return jsonify(resp)


@route_api.route("/group/invite-member")
def invite_request():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values
    user_id = int(req['user_id']) if 'user_id' in req else -1
    group_id = int(req['group_id']) if 'group_id' in req else -1
    if user_id <= 0 or group_id <= 0:
        resp['code'] = -1
        resp['msg'] = '操作错误'
        return jsonify(resp)

    tar_ass = Association.query.filter_by(group_id=group_id, user_id=user_id, status=1).first()
    if tar_ass:
        resp['code'] = -1
        resp['msg'] = "该用户已是群成员"
        return jsonify(resp)

    manager_id = Group.query.filter_by(gid=group_id, status=1).first().manager_id
    with db.auto_commit():
        join_inf_manager = Information(user_id=manager_id, member_id=user_id, manager_id=manager_id, group_id=group_id,
                                       created_time=datetime.now(),
                                       inform_type=3, status=1, is_read=0, done_type=0, is_manager=1)
        join_inf_member = Information(user_id=user_id, member_id=user_id, manager_id=manager_id, group_id=group_id,
                                      created_time=datetime.now(),
                                      inform_type=3, status=1, is_read=0, done_type=0, is_manager=0)
        db.session.add_all([join_inf_manager, join_inf_member])
    with db.auto_commit():
        join_inf_manager.ass_id = join_inf_member.id
        join_inf_member.ass_id = join_inf_manager.id
        db.session.add_all([join_inf_manager, join_inf_member])

    return jsonify(resp)
